import Taro from '@tarojs/taro'

// 请求拦截器
export function requestInterceptor(chain) {
    return chain.proceed(chain.requestParams).then(res=>{
        return res.data
    }).catch(err=>{
        console.log('err错误',err)
    })
}

// 响应拦截器——已经返回数据
export async function responseInterceptor(res,flag) {
    let code = 0
    if(flag === 'body'){
        code  = res.status
    }else{
        code = res?.code
    }
    switch(code){
        case 200:
            if(flag === 'body'){
                return res?.body
            }
            return res?.data
        case 403:
            if(flag === 'body'){
                let resjson = await res.json()
                Taro.showToast({ title: resjson?.message || 'Error', icon: 'none' });
            }else{
                Taro.showToast({ title: res?.message || 'Error', icon: 'none' });
            }
            // Unauthorized, redirect to login
            Taro.navigateTo({ url: '/pages/login/login' });
            // window.location.href = 'login'
            return 
        default:
            if(flag === 'body'){
                let resjson = await res.json()
                Taro.showToast({ title: resjson?.message || 'Error', icon: 'none' });
            }else{
                Taro.showToast({ title: res?.message || 'Error', icon: 'none' });
            }
    }
    return Promise.reject(res);
}